package com.zrwl.poscloud.xo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrwl.poscloud.base.entity.*;
import com.zrwl.poscloud.base.enums.EMessageModelType;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.config.message.ModelConfig;
import com.zrwl.poscloud.commons.utils.JsonUtils;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.commons.utils.StringUtils;
import com.zrwl.poscloud.xo.global.MessageConf;
import com.zrwl.poscloud.xo.global.SQLConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.mapper.MessageModelMapper;
import com.zrwl.poscloud.xo.mapper.UserEmployeeRMapper;
import com.zrwl.poscloud.xo.mapper.UserMapper;
import com.zrwl.poscloud.xo.service.MessageModelService;
import com.zrwl.poscloud.xo.service.MessageSmsService;
import com.zrwl.poscloud.xo.service.SequenceService;
import com.zrwl.poscloud.xo.vo.AdminVO;
import com.zrwl.poscloud.xo.vo.MessageModelVO;
import com.zrwl.poscloud.xo.vo.MessageSmsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息模板 服务实现类
 *
 * @author 刘思童 AutoGenerate
 * @date 2021-05-06
 */
@Service
@Slf4j
public class MessageModelServiceImpl extends SuperServiceImpl<MessageModelMapper, MessageModel> implements MessageModelService {

    @Autowired
    private MessageModelService messageModelService;
    @Autowired
    private SequenceService sequenceService;
    @Resource
    private MessageModelMapper messageModelMapper;
    @Autowired
    private MessageSmsService messageSmsService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserEmployeeRMapper userEmployeeRMapper;

    @Override
    public IPage<MessageModel> getPageList(MessageModelVO messageModelVO) {
        QueryWrapper<MessageModel> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(messageModelVO.getKeyword()) && !StringUtils.isEmpty(messageModelVO.getKeyword().trim())) {
            queryWrapper.like("name", messageModelVO.getKeyword().trim())
                    .or().like("content", messageModelVO.getKeyword().trim());
        }
        if (messageModelVO.getPlatformType() != 0) {
            queryWrapper.eq("platform_type", messageModelVO.getPlatformType());
        }
        Page<MessageModel> page = new Page<>();
        page.setCurrent(messageModelVO.getCurrentPage());
        page.setSize(messageModelVO.getPageSize());
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
        IPage<MessageModel> pageList = messageModelService.page(page, queryWrapper);
        List<MessageModel> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<MessageModel> getAllList(MessageModelVO messageModelVO) {
        QueryWrapper<MessageModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        List<MessageModel> list = messageModelService.list(queryWrapper);
        return list;
    }

    @Override
    public String add(MessageModelVO messageModelVO) {
        QueryWrapper<MessageModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", messageModelVO.getCode());
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        if (messageModelService.count(queryWrapper) > 0) {
            return ResultUtil.errorWithMessage(MessageConf.INSERT_SUCCESS_REPEAT);
        }
        MessageModel entity = new MessageModel();
        BeanUtils.copyProperties(messageModelVO, entity, SysConf.STATUS);
        entity.insert();
        messageModelVO.setUid(entity.getUid());
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String edit(MessageModelVO messageModelVO) {
        MessageModel entity = messageModelService.getById(messageModelVO.getUid());
        BeanUtils.copyProperties(messageModelVO, entity);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String delete(MessageModelVO messageModelVO) {
        MessageModel entity = messageModelService.getById(messageModelVO.getUid());
        entity.setStatus(EStatus.DISABLED);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public void sendMessage(MessageModelVO messageModelVO, String name, int number, String contentName, List<AdminVO> adminVOS) {

        MessageModelVO messageModelByNameAndCode = messageModelMapper.getMessageModelByNameAndCode(messageModelVO);
        String content = messageModelByNameAndCode.getContent();
        String templateId = null;
        for (AdminVO adminVO : adminVOS) {
            switch (name) {
                case "sms":
                    content = content.replace("{1}", contentName);
                    content = content.replace("{2}", (number) + "");
                    MessageSmsVO messageSmsVO = new MessageSmsVO();
                    messageSmsVO.setContent(content);
                    messageSmsService.sendMessage(adminVOS, messageSmsVO);
                case "email":
                    break;
                case "wx":
                  /*  templateId = "dqiXhja4Uia8GGKKhX1urBVyoOvANH0Ak8_T6fgkehk";
                    MessageWxVO messageWxVO = new MessageWxVO();
                    messageWxVO.setOpenId("");
                    messageWxVO.setTemplateId(templateId);
                    messageWxVO.setUrl("http://wx.yucard.cn");
                    messageWxVO.setFirst("亲爱的朋友，您所购买的产品余量不足，为了保证该产品的正常使用，请及时充值!");
                    messageWxVO.setRemark("");*/
                    break;
            }
        }
    }

    @Override
    public MessageModel getTemplateMessage(EMessageModelType platformType, int type) {
        QueryWrapper<MessageModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("platform_type", platformType.getType());
        queryWrapper.eq("type", type);
        queryWrapper.ne(SysConf.STATUS, EStatus.DISABLED);
        MessageModel model = messageModelService.getOne(queryWrapper);
        return model;
    }

    @Override
    public MessageModel getConfig(int plant, int type) {
        switch (plant) {
            case 1:
                if (ModelConfig.smsModelConfig == null)
                    refreshConfig();
                return ModelConfig.smsModelConfig.get(type);
            case 2:
                if (ModelConfig.wxModelConfig == null)
                    refreshConfig();
                return ModelConfig.wxModelConfig.get(type);
            case 3:
                if (ModelConfig.emailModelConfig == null)
                    refreshConfig();
                return ModelConfig.emailModelConfig.get(type);
            default:
                return null;
        }
    }
    /***
     * 从数据库中取到模板，然后将uid作为key 实体作为数据放到内存中
     */
    @Override
    public void refreshConfig() {
        log.info("刷新模板");
        List<MessageModel> list = messageModelMapper.getConfigList();
        Map<Integer, MessageModel> modelConfig;
        for (MessageModel messageModel : list) {
            switch (messageModel.getPlatformType()){
                case 1:
                    if(ModelConfig.smsModelConfig == null){
                        modelConfig = new HashMap<>();
                        modelConfig.put(messageModel.getType(),messageModel);
                        ModelConfig.smsModelConfig = modelConfig;
                    }else {
                        ModelConfig.smsModelConfig.put(messageModel.getType(),messageModel);
                    }
                    break;
                case 2:
                    if(ModelConfig.wxModelConfig == null){
                        modelConfig = new HashMap<>();
                        modelConfig.put(messageModel.getType(),messageModel);
                        ModelConfig.wxModelConfig = modelConfig;
                    }else {
                        ModelConfig.wxModelConfig.put(messageModel.getType(),messageModel);
                    }
                    break;
                case 3:
                    if(ModelConfig.emailModelConfig == null){
                        modelConfig = new HashMap<>();
                        modelConfig.put(messageModel.getType(),messageModel);
                        ModelConfig.emailModelConfig = modelConfig;
                    }else {
                        ModelConfig.emailModelConfig.put(messageModel.getType(),messageModel);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    @Transactional
    public String addSendMessage(MessageModelVO messageModelVO) {
        switch (messageModelVO.getPlatformType()){
            case 1:
                //短信
                addMessageSms(messageModelVO);
                break;
            case 2:
                //微信
                addMessageWx(messageModelVO);
                break;
            case 3:
                //邮件
                addMessageEmail(messageModelVO);
                break;
        }
        return null;
    }

    public void addMessageEmail(MessageModelVO messageModelVO) {
        User user = new User();
        MessageEmail messageEmail = new MessageEmail();
        messageEmail.setModelType(messageModelVO.getModelType());
        messageEmail.setToUid(messageModelVO.getToUid());
        String email = "";
        //先判断toUid是不是用户
        user = userMapper.getUserByUserUid(messageModelVO.getToUid());
        if (user == null) {
            //根据持卡人获取用户列表
            List<User> userEmployeeList = userEmployeeRMapper.getUserByEmployeeUid(messageModelVO.getToUid());
            if (userEmployeeList.size() > 0) {
                for (User userEmployee : userEmployeeList) {
                    email = userEmployee.getEmail();
                }
            }
        } else {
            email = user.getEmail();
        }
        messageEmail.setEmail(email);
        messageEmail.setContent(messageModelVO.getContent());
        MessageModelVO vo=messageModelMapper.getMessageModelByPlatAndType(messageModelVO.getPlatformType(),messageModelVO.getType());
        messageEmail.setTemplateId(vo.getCode());
        messageEmail.setUid(messageEmail.getUid());
        messageEmail.insert();
    }

    public void addMessageWx(MessageModelVO messageModelVO) {
        User user = new User();
        MessageWx messageWx = new MessageWx();
        messageWx.setModelType(messageModelVO.getModelType());
        JSONObject contentArray = JSONArray.parseObject(messageModelVO.getContent());
        String object = JsonUtils.objectToJson(contentArray);
        Map<String, Object> map = JsonUtils.jsonToMap(object);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String s = String.valueOf(entry.getValue());
            String key = entry.getKey();
            String value = (String) entry.getValue();
            messageWx.setUrl("http://wx.yucard.cn");
            if (key.contains("first")) {
                messageWx.setFirst(value);
            }
            if (key.contains("remark")) {
                messageWx.setRemark(value);
            }
        }
        messageWx.setToUid(messageModelVO.getToUid());
        String weChat = "";
        //先判断toUid是不是用户
        user = userMapper.getUserByUserUid(messageModelVO.getToUid());
        if (user == null) {
            //根据持卡人获取用户列表
            List<User> userEmployeeList = userEmployeeRMapper.getUserByEmployeeUid(messageModelVO.getToUid());
            if (userEmployeeList.size() > 0) {
                for (User userEmployee : userEmployeeList) {
                    weChat = userEmployee.getWeChat();
                }
            }
        } else {
            weChat = user.getWeChat();
        }
        messageWx.setOpenId(weChat);
        MessageModelVO vo=messageModelMapper.getMessageModelByPlatAndType(messageModelVO.getPlatformType(),messageModelVO.getType());
        messageWx.setTemplateId(vo.getCode());
        messageWx.setContent(messageModelVO.getContent());
        messageWx.setUid(messageWx.getUid());
        messageWx.insert();
    }

    public void addMessageSms(MessageModelVO messageModelVO) {
        User user = new User();
        MessageSms messageSms = new MessageSms();
        messageSms.setModelType(messageModelVO.getModelType());
        messageSms.setToUid(messageModelVO.getToUid());
        String mobile = "";
        //先判断toUid是不是用户
        user = userMapper.getUserByUserUid(messageModelVO.getToUid());
        if (user == null) {
            //根据持卡人获取用户列表
            List<User> userEmployeeList = userEmployeeRMapper.getUserByEmployeeUid(messageModelVO.getToUid());
            if (userEmployeeList.size() > 0) {
                for (User userEmployee : userEmployeeList) {
                    mobile = userEmployee.getMobile();
                }
            }
        } else {
            mobile = user.getMobile();
        }
        messageSms.setMobile(mobile);
        messageSms.setContent(messageModelVO.getContent());
        MessageModelVO vo=messageModelMapper.getMessageModelByPlatAndType(messageModelVO.getPlatformType(),messageModelVO.getType());
        messageSms.setTemplateId(vo.getCode());
        messageSms.setUid(messageSms.getUid());
        messageSms.insert();
    }

}
